package com.iflytek.iot.okhttp.Interceptor;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 *
 * @author yu 2020/9/2.
 */
public class RetryInterceptor implements Interceptor {
    public int maxRetryCount;
    private int count = 0;

    public RetryInterceptor(int maxRetryCount) {
        this.maxRetryCount = maxRetryCount;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        return retry(chain);
    }

    public Response retry(Chain chain) {
        Response response = null;
        Request request = chain.request();
        try {
            response = chain.proceed(request);
            while (!response.isSuccessful() && count < maxRetryCount) {
                count++;
                response = retry(chain);
            }
        } catch (Exception e) {
            while (count < maxRetryCount) {
                count++;
                response = retry(chain);
            }
        }
        return response;
    }
}
